package com.example.experiment3.service;

import com.example.experiment3.entity.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class CoronaVirusDataService implements InitializingBean {
    //private static final String CORONA_VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    //private static final String CORONA_VIRUS_DATA_URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private static final String CORONA_VIRUS_DATA_URL = "https://gitee.com/yangyaobo/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    public static Integer sum_1 = 0;
    public static Integer sum_2 = 0;

    private final List<RegionStats> allRegionStats = new LinkedList<>();

    @Scheduled(cron = "${yang.update.time}")
    public void fetchCoronaVirusData() throws IOException {

        RestTemplate restTemplate = new RestTemplate();

        //爬取全球新冠病毒统计数据的csv文件
        RequestEntity<Void> entity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> {httpHeaders.add("User-Agent","Mozilla/5.0");
                })
                .build();
        ResponseEntity<Resource> exchange = restTemplate.exchange(entity, Resource.class);
        Resource body = exchange.getBody();

        Reader in = new InputStreamReader(body.getInputStream(), "UTF-8");

        Iterable<CSVRecord> records = CSVFormat.DEFAULT
                .withFirstRecordAsHeader()
                .withRecordSeparator("\n")
                .withDelimiter(',')
                .withQuote('"')
                .parse(in);

        for (CSVRecord record : records) {
            int latestTotalCases = Integer.valueOf(record.get(record.size()-1));
            int diffFromPrevDay = Integer.valueOf(record.get(record.size()-1))-Integer.valueOf(record.get(record.size()-2));
            sum_1+=latestTotalCases;
            sum_2+=diffFromPrevDay;
            RegionStats rs = new RegionStats(record.get("Province/State"), record.get("Country/Region"), Integer.parseInt(record.get(record.size() - 1)), Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
            allRegionStats.add(rs);
        }

    }

    //全球总数据
    public List<RegionStats> getAllRegionStats() {return allRegionStats;}

    //通过关键字key查询地区数据
    public List<RegionStats> findRegionDataByKey(String key){

        List<RegionStats> list_1 = allRegionStats.stream().filter((s)->s.getCountry().equals(key)).collect(Collectors.toList());


        if(list_1.isEmpty()) {
            List<RegionStats> list_2 = allRegionStats.stream().filter((s) -> s.getState().equals(key)).collect(Collectors.toList());
            return list_2;
        }
        else
            return list_1;

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }
}
